// RobotConfigManager.js

class RobotConfigManager {
    constructor() {
        this.config = null;
    }

    // 加载配置
    loadConfig() {
        return fetch('/scripts/config/robot-config.json')
            .then(response => response.json())
            .then(config => {
                this.config = this.processConfig(config);
                // 设置全局配置
                window.robotConfig = this.config;  // 改用window.robotConfig
                return this.config;
            })
            .catch(error => {
                console.error('Error loading robot configuration:', error);
                throw error;
            });
    }

    // 处理配置（转换颜色值等）
    processConfig(config) {
        const processedConfig = JSON.parse(JSON.stringify(config)); // 深拷贝
        this.convertColors(processedConfig);
        return processedConfig;
    }

    // 递归转换颜色值
    convertColors(obj) {
        for (let key in obj) {
            if (typeof obj[key] === 'object' && obj[key] !== null) {
                this.convertColors(obj[key]);
            } else if (key.toLowerCase().includes('color') && typeof obj[key] === 'string') {
                obj[key] = parseInt(obj[key].replace('#', '0x'), 16);
            }
        }
    }

    // 获取完整配置
    getConfig() {
        return this.config;
    }

    // 获取特定组件的配置
    getComponentConfig(componentName) {
        return this.config[componentName];
    }

    // 获取特定配置值
    getValue(path) {
        return path.split('.').reduce((obj, key) => obj && obj[key], this.config);
    }

    // 验证配置
    validateConfig() {
        if (!this.config) return false;

        const robotDiameterInCells = this.config.world.reference.robot_diameter /
                                   this.config.world.grid.cell_size_meters;
        console.log(`Robot diameter covers ${robotDiameterInCells} grid cells`);

        if (Math.abs(robotDiameterInCells - this.config.world.reference.grid_cells_per_robot) > 0.1) {
            console.warn('Grid cell size might need adjustment');
        }

        return true;
    }
}
// 创建全局配置管理器实例
const configManager = new RobotConfigManager();

// 导出到全局作用域
if (typeof window !== 'undefined') {
    window.configManager = configManager;
    window.RobotConfigManager = RobotConfigManager;
}

// CommonJS 模块导出
if (typeof module !== 'undefined' && module.exports) {
    module.exports = {
        RobotConfigManager
    };
}